package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.RelativeDateFormat;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.CommentVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.QuanZiVo;
import com.tanhua.server.vo.VisitorsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@Service
public class QuanZiService {

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    private QuanziMQService quanziMQService;
    /**
     * 查询好友动态
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryPublishList(Integer page, Integer pageSize/*, String token*/) {
        //构建返回值PageResult对象
        PageResult pageResult = new PageResult();

        //校验token是否有效
//        User user = userService.queryUserByToken(token);
//        if (user == null) {
//            //token已经失效
//            return pageResult;
//        }

        //直接从ThreadLocal获取user
        User user = UserThreadLocal.get();

        //1.通过dubbo查询数据 - 发布动态数据Publish集合
        PageInfo<Publish> pageInfo = quanZiApi.queryPublishList(user.getId(), page, pageSize);
        //2.获取分页信息中集合对象 - Publish集合
        List<Publish> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }

        //3.构建一个QuanZiVo集合，并封装里面的每条数据
        List<QuanZiVo> quanZiVoList = new ArrayList<>();
        //3.1 遍历Publish集合 - 获取每条发布动态信息，封装到每个QuanZiVo对象
        for (Publish publish : records) {
            QuanZiVo quanZiVo = new QuanZiVo();
            quanZiVo.setId(publish.getId().toHexString());                              //发布动态id
            quanZiVo.setTextContent(publish.getText());                                 //发布文字
            quanZiVo.setImageContent(publish.getMedias().toArray(new String[]{}));      //发布图片
            quanZiVo.setUserId(publish.getUserId());                                    //发布用户id
            quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));  //发布距现在时间

            quanZiVoList.add(quanZiVo);
        }
        /*records.forEach(publish -> {
            QuanZiVo quanZiVo = new QuanZiVo();
            quanZiVo.setId(publish.getId().toHexString());
            quanZiVo.setTextContent(publish.getText());
            quanZiVo.setImageContent(publish.getMedias().toArray(new String[]{}));
            quanZiVo.setUserId(publish.getUserId());
            quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));

            quanZiVoList.add(quanZiVo);
        });*/

        //4.查询用户信息
        //4.1 构建userInfo的id集合
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        //4.2 根据所有userId查询UserInfo信息
        List<UserInfo> userInfoList = userInfoService.queryUserInfoByUserIdList(userIds);
        //4.3 构建剩余部分QuanZiVo对象信息
        for (QuanZiVo quanZiVo : quanZiVoList) {
            //找到对应的用户信息
            for (UserInfo userInfo : userInfoList) {
                if (quanZiVo.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    //4.4 调用方法进行封装
                    fillUserInfoToQuanZiVo(userInfo, quanZiVo);
                    break;
                }
            }
        }

        //5.封装PageResult对象进行返回
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setItems(quanZiVoList);
        return pageResult;
    }

    /**
     * 填充用户信息
     *
     * @param userInfo
     * @param quanZiVo
     */
    private void fillUserInfoToQuanZiVo(UserInfo userInfo, QuanZiVo quanZiVo) {
        //1.调用HuTool工具BeanUtil工具类
        BeanUtil.copyProperties(userInfo, quanZiVo, "id");
        quanZiVo.setGender(userInfo.getSex().name().toLowerCase());
        quanZiVo.setTags(StringUtils.split(userInfo.getTags(), ','));

        //当前用户
        User user = UserThreadLocal.get();

        quanZiVo.setCommentCount(0); //TODO 评论数
        quanZiVo.setDistance("1.2公里"); //TODO 距离
        quanZiVo.setHasLiked(this.quanZiApi.queryUserIsLike(user.getId(), quanZiVo.getId()) ? 1 : 0); //是否点赞（1是，0否）
        quanZiVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(quanZiVo.getId()))); //点赞数
        quanZiVo.setHasLoved(quanZiApi.queryUserIsLove(user.getId(),quanZiVo.getId())?1:0); //TODO 是否喜欢（1是，0否）
        quanZiVo.setLoveCount(Convert.toInt(quanZiApi.queryLoveCount(quanZiVo.getId()))); //TODO 喜欢数
    }

    //==============================================================================================


    /**
     * 发布动态
     *
     * @param textContent   文字动态
     * @param location      位置
     * @param latitude      经度
     * @param longitude     纬度
     * @param multipartFile 图片动态（支持多张图片）
     * @return
     */
    public String savePublish(String textContent, String location, String latitude, String longitude, MultipartFile[] multipartFile) {
        //1.查询当前的登录信息
        User user = UserThreadLocal.get();

        //2.1 构建一个发布动态对象
        Publish publish = new Publish();
        publish.setUserId(user.getId());
        publish.setText(textContent);
        publish.setLocationName(location);
        publish.setLatitude(latitude);
        publish.setLongitude(longitude);
        publish.setSeeType(1);

        //2.2 获取发布图片存储地址集合
        List<String> picUrls = new ArrayList<>();
        //图片上传
        for (MultipartFile file : multipartFile) {
            PicUploadResult picUploadResult = picUploadService.upload(file);
            //将图片发布路径保存到图片地址集合中
            picUrls.add(picUploadResult.getName());
        }

        publish.setMedias(picUrls);

        String publishId = quanZiApi.savePublish(publish);

        if(StrUtil.isNotEmpty(publishId)){
            //发送消息
            this.quanziMQService.publishMsg(publishId);
        }
        return publishId;
    }

    /**
     * 查询推荐动态
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryRecommendPublishList(Integer page, Integer pageSize) {
        //直接从ThreadLocal中获取对象
        User user = UserThreadLocal.get();

        PageResult pageResult = new PageResult();

        //通过dubbo查询数据
        PageInfo<Publish> pageInfo = quanZiApi.queryRecommendPublishList(user.getId(), page, pageSize);
        List<Publish> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }

        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setItems(fillQuanZiVo(records));
        return pageResult;
    }

    /**
     * 根据查询到的publish集合填充QuanZiVo对象
     *
     * @param records
     * @return
     */
    private List<QuanZiVo> fillQuanZiVo(List<Publish> records) {
        List<QuanZiVo> quanZiVoList = new ArrayList<>();
        records.forEach(publish -> {
            QuanZiVo quanZiVo = new QuanZiVo();
            quanZiVo.setId(publish.getId().toHexString());
            quanZiVo.setTextContent(publish.getText());
            quanZiVo.setImageContent(publish.getMedias().toArray(new String[]{}));
            quanZiVo.setUserId(publish.getUserId());
            quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));

            quanZiVoList.add(quanZiVo);
        });

        //查询用户信息 获取给定Bean列表中指定字段名对应字段值的列表
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = userInfoService.queryUserInfoByUserIdList(userIds);
        for (QuanZiVo quanZiVo : quanZiVoList) {
            //找到对应的用户信息
            for (UserInfo userInfo : userInfoList) {
                if (quanZiVo.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    fillUserInfoToQuanZiVo(userInfo, quanZiVo);
                    break;
                }
            }
        }

        return quanZiVoList;
    }
    //动态点赞
    public Long likeComment(String publishId) {
        User user = UserThreadLocal.get();
        //点赞
        Boolean result = this.quanZiApi.likeComment(user.getId(), publishId);
        if (result) {
            //点赞消息发送
            quanziMQService.likePublishMsg(publishId);
            //查询点赞数
            return this.quanZiApi.queryLikeCount(publishId);
        }
        return null;
    }
    //取消动态点赞
    public Long disLikeComment(String publishId) {
        User user = UserThreadLocal.get();
        //取消点赞
        Boolean result = this.quanZiApi.disLikeComment(user.getId(), publishId);
        if (result) {
            //发消息
            quanziMQService.disLikePublishMsg(publishId);
            //查询点赞数
            return this.quanZiApi.queryLikeCount(publishId);
        }
        return null;
    }

   //喜欢
    public Long loveComment(String publishId) {
        User user = UserThreadLocal.get();
        Boolean comment = quanZiApi.loveComment(user.getId(), publishId);
        if (comment) {
            //发消息
            quanziMQService.lovePublishMsg(publishId);

            return quanZiApi.queryLoveCount(publishId);
        }
        return null;
    }
   //取消喜欢
    public Long disLoveComment(String publishId) {
        User user = UserThreadLocal.get();
        Boolean aBoolean = quanZiApi.disLoveComment(user.getId(), publishId);
        if (aBoolean) {
            //发消息
            quanziMQService.disLovePublishMsg(publishId);

            return quanZiApi.queryLoveCount(publishId);
        }
        return null;
    }
//查询评论列表
    public PageResult queryCommentList(String publishId, Integer page, Integer pageSize) {

        PageResult result = new PageResult();
        result.setPage(page);
        result.setPagesize(pageSize);
        PageInfo<Comment> pageInfo = quanZiApi.queryCommentList(publishId, page, pageSize);
        List<Comment> records = pageInfo.getRecords();
        if (records == null){
            return result;
        }
        User user = UserThreadLocal.get();
        List<CommentVo> list = new ArrayList<>();
        for (Comment record : records) {
            CommentVo commentVo =new CommentVo();
            UserInfo userInfo = userInfoService.queryUserInfoByUserId(record.getUserId());
            commentVo.setContent(record.getContent());
            commentVo.setId(record.getId().toHexString());
            commentVo.setCreateDate(DateUtil.format(new Date(record.getCreated()), "HH:mm"));
            //是否点赞
            commentVo.setHasLiked(this.quanZiApi.queryUserIsLike(user.getId(), commentVo.getId()) ? 1 : 0);
            //点赞数
            commentVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(commentVo.getId())));

            commentVo.setAvatar(userInfo.getLogo());
            commentVo.setNickname(userInfo.getNickName());
         list.add(commentVo);
        }
        if (list==null){
            return result;
        }
        result.setItems(list);
        return result;
    }
     //发表评论
    public Boolean saveComments(String publishId, String content) {
        User user = UserThreadLocal.get();
        Boolean result = quanZiApi.saveComment(user.getId(), publishId, content);
        if (result){
            //发消息
            quanziMQService.commentPublishMsg(publishId);
        }
        return result;
    }
   //浏览动态
    public QuanZiVo queryById(String publishId) {
        Publish publish = this.quanZiApi.queryPublishById(publishId);
        if (publish == null) {
            return null;
        }
        //发消息
        quanziMQService.queryPublishMsg(publishId);
        return this.fillQuanZiVo(Arrays.asList(publish)).get(0);
    }

    //自己的所有动态
    public PageResult queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        //查询数据
        PageInfo<Publish> pageInfo = this.quanZiApi.queryAlbumList(userId, page, pageSize);
        if(CollUtil.isEmpty(pageInfo.getRecords())){
            return pageResult;
        }

        //填充数据
        pageResult.setItems(this.fillQuanZiVo(pageInfo.getRecords()));

        return pageResult;
    }


    //谁看过我
    public List<VisitorsVo> queryVisitorsList() {
        User user = UserThreadLocal.get();
        List<Visitors> visitorsList = this.visitorsApi.queryMyVisitor(user.getId());
        if (CollUtil.isEmpty(visitorsList)) {
            return Collections.emptyList();
        }

        List<Object> userIds = CollUtil.getFieldValues(visitorsList, "visitorUserId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByUserIdList(userIds);

        List<VisitorsVo> visitorsVoList = new ArrayList<>();

        for (Visitors visitor : visitorsList) {
            for (UserInfo userInfo : userInfoList) {
                if (ObjectUtil.equals(visitor.getVisitorUserId(), userInfo.getUserId())) {

                    VisitorsVo visitorsVo = new VisitorsVo();
                    visitorsVo.setAge(userInfo.getAge());
                    visitorsVo.setAvatar(userInfo.getLogo());
                    visitorsVo.setGender(userInfo.getSex().name().toLowerCase());
                    visitorsVo.setId(userInfo.getUserId());
                    visitorsVo.setNickname(userInfo.getNickName());
                    visitorsVo.setTags(StringUtils.split(userInfo.getTags(), ','));
                    visitorsVo.setFateValue(visitor.getScore().intValue());

                    visitorsVoList.add(visitorsVo);
                    break;
                }
            }
        }

        return visitorsVoList;
    }
}
